﻿/* Copyright (c) 2015 Slava Naumenko - http://m4w.codeplex.com */

using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Services;

namespace M4W.ASM.Services
{
    [WebService(Namespace = "M4W.ASM.Services")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    [System.ComponentModel.ToolboxItem(false)]
    public class Calendar : System.Web.Services.WebService
    {
        [WebMethod]
        public string GenerateICS(string List, string ItemId, string Name)
        {
            string result = "";
            try
            {
                result = CalendarGenerateICS.Invoke(List, ItemId, Name);
            }
            catch (Exception ex)
            {
                result = ex.Message.ToString();
            }
            return result;
        }
    }

    // Invocations

    internal static class CalendarGenerateICS
    {
        internal static string Invoke(string List, string ItemId, string Name)
        {
            string result = "";

            string curl = Helper.GetCurrentUrl();

            using (SPSite site = new SPSite(curl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;

                    SPList list = Helper.GetList(web, List);
                    if (list == null)
                    {
                        result = "List '" + List + "' not found.";
                    }
                    else
                    {
                        SPListItem item = list.GetItemById(Int16.Parse(ItemId));

                        string ics = "";

                        ics += "BEGIN:VCALENDAR\n";
                        ics += "PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN";
                        ics += "VERSION:2.0\n";
                        ics += "CALSCALE:GREGORIAN";
                        ics += "METHOD:REQUEST\n";
                        ics += "BEGIN:VEVENT\n";
                        ics += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED\n";
                        ics += "TRANSP:OPAQUE\n";
                        ics += "SEQUENCE:0\n";
                        ics += "DTSTART:" + FormatDate((DateTime)item["EventDate"]) + "\n";
                        ics += "DTEND:" + FormatDate((DateTime)item["EndDate"]) + "\n";
                        ics += "DTSTAMP:" + FormatDate((DateTime)item["Created"]) + "\n";
                        ics += "X-ALT-DESC;FMTTYPE=text/html:" + item["Description"].ToString() + "\n";
                        ics += "PRIORITY:5\n";
                        ics += "STATUS:CONFIRMED\n";
                        ics += "SUMMARY:" + item["Title"].ToString() + "\n";
                        ics += "LOCATION:" + item["Location"].ToString() + "\n";
                        ics += "END:VEVENT\n";
                        ics += "END:VCALENDAR\r\n";

                        string name = Name + ".ics";

                        List<string> fileNames = new List<string>();

                        foreach (string fileName in item.Attachments)
                        {
                            fileNames.Add(fileName);
                        }

                        foreach (string file in fileNames)
                        {
                            if (file == name) { item.Attachments.Delete(name); }
                        }

                        item.Attachments.Add(name, Helper.GetBytes(ics));

                        item.SystemUpdate();

                        result = "ICS Attached: '" + name + "'.";
                    }

                    web.AllowUnsafeUpdates = false;
                }
            }

            return result;
        }

        internal static string FormatDate(DateTime date)
        {
            string result = "";

            CultureInfo enus = new CultureInfo("en-US");

            result = date.ToString("s", enus).Replace("-", "").Replace(":", "");

            return result;
        }
    }
}